package com.frank.libandroid.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;

import com.frank.libandroid.ReflectUtil;
import com.frank.libandroid.butterknife.ButterKnife;

import java.lang.reflect.InvocationTargetException;

public class BaseView<V extends ViewDataBinding> extends FrameLayout {
    protected String TAG = this.getClass().getSimpleName();
    private Object bean;

    public BaseView(@NonNull Context context) {
        super(context);
    }

    public BaseView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public BaseView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setBean(Object bean) {
        Log.d(TAG, "setBean() called with: bean = [" + bean + "]");
        mBinding.setVariable(1, bean);
        this.bean = bean;
    }

    public <T> T getBean() {
        return (T) bean;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        Class<Object> generic = (Class<Object>) ReflectUtil.getGeneric(this, 0);
        try {
            mBinding = (V) generic.getMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class).invoke(null, LayoutInflater.from(getContext()), this, true);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        initView();
    }

    public V mBinding;


    protected void initView() {
        ButterKnife.bind(this, mBinding.getRoot());
    }
}
